<?php

namespace App\Http\Controllers\AdminApi\User;

use Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Validation\ValidationException;
use App\User;
use App\Http\Models\Home\EmailCaptcha;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Traits\EmailSendTrait;
use App\Http\Models\Admin\Permission_;
use App\Http\Models\Admin\ClassifyPermissions;
use App\Http\Models\Admin\Role_;
use Illuminate\Support\Facades\Hash as FacadesHash;
use Illuminate\Support\Facades\DB;




class LoginController extends Controller
{
    // use ThrottlesLogins;
    //用户登录
    public function Login(Request $request)
    {
        // return 1;
        // echo 1;die;
        //判断用户失败登录频率
        //  if ($this->hasTooManyLoginAttempts($request)) {
        //     return $this->sendLockoutResponse($request);
        // }

        $username = $request->get('username');
        $password = $request->get('password');
        if (empty($username)) {
            return response()->json(['message' => '请输入用户名', 'status' => 0, 'data' => null]);
        }
        if (empty($password)) {
            return response()->json(['message' => '请输入密码', 'status' => 0, 'data' => null]);
        }
        //已经封装好的数据库查询语句
        // redaySql(new DB);
        $user = User::orWhere('username', $username)->first();
        // showSql(new DB);
        if ($user && ($user->status == 1)) {
            return response()->json(['message' => '该用户已被禁止登录', 'status' => 0, 'data' => null]);
        }
        if (!$user) {
            return response()->json(['message' => '用户不存在', 'status' => 0, 'data' => null]);
        }

        // $this->incrementLoginAttempts($request);
        if (!$user || !FacadesHash::check($request->password, $user->password)) {
            // if (!$user || !Auth::attempt(['name' => trim($username), 'password' => trim($password)])) {
            return response()->json(['message' => '用户名或密码错误', 'status' => 0, 'data' => null]);
        }

        // 更新 api_key
        $api_token = uniqid($user->id);
        $user->api_token = $api_token;
        $user->login_ip = $request->getClientIp();
        $user->save();
        $result = [
            'user' => $user,
            'token' => $user->api_token
        ];
        // echo $result;
        // $this->clearLoginAttempts($request);
        return response()->json(['code' => 20000, 'message' => '登录成功',  'data' => $result]);
    }

    //获取当前登录用户信息
    public function info()
    {
        $uid = Auth::guard('adminapi')->user()->id;
        $user = User::where(array('id' => $uid))->first();
        $userRolesId = $user->roles()->pluck('id');
        // $permission = new Permission_();
        // $permissions = $permission::
        // with(['role_belongsToMany' => function ($query) use ($userRolesId) {
        //     $query->select()
        //         ->where('role_id', $userRolesId);
        // }])
        // ->
        // get();

        $Role = new Role_();
        $Role = $Role::with(['hasManyDetails' => function ($query) {
            // $query->select()
            // ->where('role_id', $userRolesId);
        }])
            ->where('id', $userRolesId);
        $Roles = $Role->first();

        $hasManyDetails_ids = $Roles->hasManyDetails->pluck('id');
        // $item_ids =$Roles->hasManyDetails->items->pluck('id'); 
        // $item_ids =$Roles; 
        // redaySql(new DB);

        $hasManyDetails = Permission_::with(['classify_belongsToMany' => function ($query) {
            // $query->select()
            // ->where('role_id', $userRolesId);
            // $query->groupBy('id');
        }])
            ->whereIn('id', $hasManyDetails_ids)
            ->where([['name', 'like', 'watch %']])
            // ->groupBy('hasDetails.id')
            ->get();

        $hasManyDetails = empty($hasManyDetails) ? array() : $hasManyDetails->toArray();
        // showSql(new DB);
        // die;
        // $hasManyDetails= $hasManyDetails->items->classify_belongsToMany->pluck('id');
        $classify_belongsToMany = [];
        if (!empty($hasManyDetails)) {
            foreach ($hasManyDetails as $key => $value) {
                if (!empty($value['classify_belongs_to_many'])) {
                    foreach ($value['classify_belongs_to_many'] as $c_key => $c_value) {
                        if ($c_value['disabled'] != 1 && is_null($c_value['deleted_at'])) {
                            $classify_belongsToMany[] = $c_value;
                        }
                    }
                    unset($c_key, $c_value);
                }
            }
            unset($key, $value);
        }

        $classifys = [];
        foreach ($classify_belongsToMany as $key => $value) {
            // 递归查询上级栏目
            // redaySql(new DB);
            // var_dump($value);die;
            $classify = ClassifyPermissions::where([['id', '=', $value['parent_id']]])->first();
            if (!empty($classify)) {
                $classify_belongsToMany[] = $classify->toArray();
            }
            // showSql(new DB);
        }
        unset($key, $value);
        $classify_belongsToMany = assoc_unique($classify_belongsToMany, 'id');

        foreach ($classify_belongsToMany as $key => $value) {
            if ($value['parent_id'] == 0) {
                $value['children'] = $this->get_down_tree($value['id'],  $classify_belongsToMany);
                $classifys[$key] = $value;
            }
        }

        $classifys = arraySort($classifys, 'rank', 'desc');

        $arr = [];
        $user->per =  $Roles->hasManyDetails;
        $user->perClass =  $classifys;

        $user->role =  $user->roles()->pluck('name');

        // var_dump($permissions);die;
        // $user->roles=['admin'];
        return response()->json(['code' => 20000, 'message' => '获取当前用户信息成功',  'data' => $user]);
    }

    //递归查询下级
    public function get_down_tree($agentid,  &$effective_commissions)
    {
        global $_W;
        global $_GPC;

        $effectives = [];

        foreach ($effective_commissions as $key => $value) {
            if ($value['parent_id'] == $agentid) {
                $effectives[] = $value;
                unset($effective_commissions[$key]);
            }
        }

        unset($value, $key);
        $childeren = array();
        foreach ($effectives as $key => $value) {
            $childeren = $this->get_down_tree($value['id'],  $effective_commissions);
            if (!empty($childeren)) {
                $effectives[$key]['children'] = $childeren;
            }
        }
        return  $effectives;
    }

    //退出登录
    public function logout()
    {
        $uid = Auth::guard('adminapi')->user()->id;
        $user = User::where(array('id' => $uid))->first();
        // $user->roles=['admin'];
        return response()->json(['code' => 20000, 'message' => '退出成功',  'data' => $user]);
    }
}
